
from typing import Any, Dict, List, Optional
from pydantic import BaseModel
from enum import Enum


class PlanType(Enum):
    """规划类型"""
    SEQUENTIAL = "sequential"       # 依次执行步骤
    PARALLEL = "parallel"           # 在可能的情况下并行执行步骤
    CONDITIONAL = "conditional"     # 根据条件执行步骤
    ITERATIVE = "iterative"         # 重复执行步骤，直到满足条件为止


class PlanStep(BaseModel):
    id: str
    description: str
    tool: str
    input_template: str
    dependencies: List[str]
    conditions: Optional[Dict[str, Any]] = None
    expected_output: Optional[str] = None
    confidence: float = 0.5
    metadata: Optional[Dict[str, Any]] = None

    def __post_init__(self):
        self.metadata = self.metadata or {}


class Plan(BaseModel):
    id: str
    query: str
    goal: str
    plan_type: PlanType
    steps: List[PlanStep]
    estimated_duration: float
    confidence: float
    metadata: Optional[Dict[str, Any]] = None
    created_at: float

    def get_executable_steps(self, completed_steps: List[str]) -> List[PlanStep]:
        """在已完成部分步骤的情况下，获取剩余可执行的步骤。"""
        executable = []
        for step in self.steps:
            if step.id not in completed_steps:
                # 检查依赖步骤是否已完成。
                if all(dep in completed_steps for dep in step.dependencies):
                    executable.append(step)
        return executable

    def is_complete(self, completed_steps: List[str]) -> bool:
        """检查计划是否已完成"""
        return all(step.id in completed_steps for step in self.steps)
